<?php

/**
 * Created by PhpStorm.
 * User: JS
 * Date: 2019/2/13
 * Time: 13:50
 */
require_once __DIR__ . '/vendor/autoload.php';
use GuzzleHttp\Client;
use Symfony\Component\Cache\Simple\FilesystemCache;
use Psr\SimpleCache\CacheInterface;
class IP360Client
{
    public $cache;
    public function __construct(CacheInterface $cache = null)
    {
        if ($cache == null) {
            $cache = new NullCache();
        }
        $this->setCache($cache);
    }

    public function Request($ip)
    {
        $client = new Client();
        $response = $client->get('http://ip.360.cn/IPQuery/ipquery',[
            'query' => [
                'ip' => $ip
            ]
        ]);
        if ($response->getStatusCode() != 200) {
            throw new Exception('remote gateway error');
        }
        $content = $response->getBody()->getContents();
        return $this->Parse($content);
    }


    public function Parse($content)
    {
        $contentarr = json_decode($content);
        return $contentarr->data;
    }

    /**
     * @param CacheInterface $cache
     */
    public function setCache($cache)
    {
        $this->cache = $cache;
        return $this;
    }


    public function lookup($ip)
    {
        $key = md5($ip);
        if ($this->cache->has($key)) {
            $data = $this->cache->get($key);
        } else {
            $data = $this->request($ip);
            $this->cache->set($key, $data);
        }
        return $data;
    }
}